package com.imooc.miaoshaproject.controller;

import com.imooc.miaoshaproject.service.OrderService;
import com.imooc.miaoshaproject.exceptions.ServiceException;
import com.imooc.miaoshaproject.exceptions.ErrorCodeEnum;
import com.imooc.miaoshaproject.response.R;
import com.imooc.miaoshaproject.service.model.OrderModel;
import com.imooc.miaoshaproject.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单接口
 *
 * @author chenjianfei
 */
@Controller("order")
@RequestMapping("/order")
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
public class OrderController extends BaseController {
    private final OrderService orderService;
    private final HttpServletRequest httpServletRequest;

    public OrderController(OrderService orderService, HttpServletRequest httpServletRequest) {
        this.orderService = orderService;
        this.httpServletRequest = httpServletRequest;
    }

    /**
     * 封装下单请求
     *
     * @param itemId  商品编号
     * @param amount  数量
     * @param promoId 秒杀活动ID
     */
    @PostMapping(value = "/createorder", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public R createOrder(@RequestParam(name = "itemId") Integer itemId,
                         @RequestParam(name = "amount") Integer amount,
                         @RequestParam(name = "promoId", required = false) Integer promoId) throws ServiceException {

        Boolean isLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (isLogin == null || !isLogin) {
            throw new ServiceException(ErrorCodeEnum.USER_NOT_LOGIN, "用户还未登陆，不能下单");
        }

        //获取用户的登陆信息
        UserModel userModel = (UserModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");
        orderService.createOrder(userModel.getId(), itemId, promoId, amount);
        return R.create(null);
    }
}
